import React, { Component } from 'react';

function withErrorBoundary(WrappedComponent) {
  class WithErrorBoundaryComponent extends Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }

    static getDerivedStateFromError() {
      return { hasError: true };
    }

    componentDidCatch(error, info) {
      // 处理错误记录
      console.error('Error:', error, 'Info:', info);
    }

    render() {
      if (this.state.hasError) {
        return <div>Something went wrong. Please try again later.</div>;
      }
      return <WrappedComponent {...this.props} />;
    }
  }

  return WithErrorBoundaryComponent;
}

export default withErrorBoundary;

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    // 初始化error的状态
    this.state = { hasError: false };
  }

  // 当error发生，设置这个状态为true
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // 处理错误记录
    console.error('Error:', error, 'Info:', info);
  }

  render() {
    // 如果error发生，返回一个回退组件
    if (this.state.hasError) {
      return <>Oh no! Epic fail!</>;
    }

    return this.props.children;
  }
}
